import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import Layout from "../views/layout/index.vue";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

const routes: Array<RouteRecordRaw> = [
  { path: "/", redirect: "/login" },
  {
    path: "/login",
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/error",
    component: () => import("@/views/error/index.vue"),
  },
];

export const serviceRouter: Array<RouteRecordRaw> = [
  {
    path: "/home",
    component: Layout,
    meta: { title: "首页", icon: "icon-home" },
    children: [
      {
        path: "index",
        component: () => import("@/views/home/index.vue"),
      },
    ],
  },
  {
    path: "/table",
    component: Layout,
    meta: { title: "表格", icon: "icon-table" },
    children: [
      {
        path: "index",
        component: () => import("@/views/table/index.vue"),
      },
    ],
  },
  {
    path: "/form",
    component: Layout,
    meta: { single: true },
    children: [
      {
        path: "index",
        meta: { title: "表单", icon: "icon-orderform" },
        component: () => import("@/views/form/index.vue"),
      },
      {
        path: "collapse/:id",
        component: () => import("@/views/collapse/index.vue"),
        meta: { title: "折叠面板", hidden: true },
      },
    ],
  },

  {
    path: "/components",
    component: Layout,
    meta: { title: "组件", icon: "icon-zujian" },
    children: [
      {
        path: "steps",
        component: () => import("@/views/steps/index.vue"),
        meta: { title: "步骤条" },
      },
      {
        path: "timeline",
        component: () => import("@/views/timeline/index.vue"),
        meta: { title: "时间线" },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

interface checkRoute {
  route: RouteRecordRaw;
  flag: boolean;
}

router.beforeEach((to, from) => {
  NProgress.start();
  if (sessionStorage.getItem("token")) {
    if (to.path == "/login") {
      NProgress.done();
      return false;
    } else {
      if (hasRoute(to)) {
        const result: checkRoute = generateRoute(to, serviceRouter);
        // result.flag 判断是否有匹配到的路由, false则跳转到404页面
        if (result.flag) {
          router.addRoute(result.route);
          return to.fullPath;
        } else {
          return "/error";
        }
      }
    }
  } else {
    if (to.path != "/login") {
      NProgress.done();
      return "/login";
    } else {
      return true;
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});

export default router;

// 判断是否存在已添加的路由
const hasRoute = (to: any): boolean => {
  let flag = true;
  router.getRoutes().map((item: any) => {
    // 判断是否存在动态路由
    if (item.path.indexOf("/:") != -1) {
      if (to.path.indexOf(item.path.substr(0, item.path.indexOf("/:"))) != -1) {
        flag = false;
      }
    } else {
      if (item.path == to.path) {
        flag = false;
      }
    }
  });

  return flag;
};

// 返回当前需要跳转的路由对象
const generateRoute = (to: any, list: Array<any>): checkRoute => {
  let index: number = 0;
  let flag: boolean = false;
  let toArr: string = to.path.substr(0, to.path.indexOf("/", 1));
  list.map((item: any, i: number) => {
    if (item.path == toArr) {
      item.children.map((v: any) => {
        // 判断是否有动态路由
        if (v.path.indexOf("/:") != -1) {
          if (to.path.indexOf(`${toArr}/${v.path.substr(0, v.path.indexOf("/:"))}`) != -1) {
            index = i;
            flag = true;
          }
        } else {
          if (to.path == `${toArr}/${v.path}`) {
            index = i;
            flag = true;
          }
        }
      });
    }
  });

  return { route: list[index], flag };
};
